{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y2eqHW0TK87s"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/drive/1P4ue133ZB5OEj8blmkyTLdmz4OiPF8DA?usp=sharing\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
        "\n",
        "### 🌳 Tree of Thoughts (ToT)\n",
        "\n",
        "Tree of Thoughts is an advanced prompting method that explores multiple reasoning paths simultaneously.\n",
        "\n",
        "### Key points:\n",
        "\n",
        "* 🔑 **Core concept:** Generates and evaluates multiple \"thoughts\" at each step of reasoning.\n",
        "\n",
        "* 📊 **Structure:** Creates a tree-like structure of potential solution paths.\n",
        "\n",
        "* ⚙️ **Process:**\n",
        "  * Generate multiple initial thoughts\n",
        "  * Evaluate and expand promising thoughts\n",
        "  * Prune less promising branches\n",
        "  * Iterate until reaching a solution\n",
        "\n",
        "* 🌟 **Advantages:**\n",
        "  * Explores diverse problem-solving approaches\n",
        "  * Reduces chances of getting stuck in suboptimal reasoning paths\n",
        "\n",
        "* 💼 **Applications:** Complex problem-solving, strategic planning, creative tasks.\n",
        "\n",
        "* 🚀 **Implementation:** Requires careful prompting to guide thought generation and evaluation.\n",
        "\n",
        "* 🔑 **Key components:**\n",
        "  * Thought generator\n",
        "  * State evaluator\n",
        "  * Search algorithm (e.g., breadth-first, depth-first)\n",
        "\n",
        "* ⚖️**Challenges:** Balancing exploration breadth with computational efficiency."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "KI4D1HL-LKaP",
        "outputId": "fe1b67d8-d663-4983-e135-3a79d61c9f88"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/121.9 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m121.9/121.9 kB\u001b[0m \u001b[31m7.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h"
          ]
        }
      ],
      "source": [
        "!pip install -q -U langchain-groq>=0.2.4"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "dfHHptAFLMwj"
      },
      "outputs": [],
      "source": [
        "from langchain_groq import ChatGroq\n",
        "from langchain.prompts import ChatPromptTemplate"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "eZJGDTIMLOnP"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import getpass"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rQrlkg_bLRZp"
      },
      "source": [
        "### 🔑 Provide Groq API Key\n",
        "\n",
        "- [Groq API Key](https://console.groq.com/keys)\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XI8sLK8uLTht",
        "outputId": "921e9c0e-63e9-4f13-e5ec-f3dce29cd8f0"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "··········\n"
          ]
        }
      ],
      "source": [
        "os.environ[\"GROQ_API_KEY\"] = getpass.getpass()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0os_AIehLVh1"
      },
      "outputs": [],
      "source": [
        "llm = ChatGroq(\n",
        "    model=\"llama-3.1-8b-instant\",\n",
        "    temperature=0.5\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "FToKQB7jLBYD"
      },
      "outputs": [],
      "source": [
        "tot_prompt = ChatPromptTemplate.from_messages(\n",
        "    [\n",
        "        (\"system\", \"You are an AI that can explore multiple solution paths for complex problems.\"),\n",
        "        (\"human\", \"\"\"Explore multiple solution paths for this problem:\n",
        "        {input}\n",
        "\n",
        "        Generate three different approaches, then evaluate and choose the best one:\n",
        "\n",
        "        Approach 1:\n",
        "        [Generate first approach]\n",
        "\n",
        "        Approach 2:\n",
        "        [Generate second approach]\n",
        "\n",
        "        Approach 3:\n",
        "        [Generate third approach]\n",
        "\n",
        "        Evaluation:\n",
        "        [Evaluate the three approaches]\n",
        "\n",
        "        Best Solution:\n",
        "        [Choose and explain the best solution]\"\"\"),\n",
        "        ]\n",
        ")\n",
        "\n",
        "chain = tot_prompt | llm"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "0PWEvnMyLZSb",
        "outputId": "c4f41bae-21ce-4d9f-f246-79a5bc843589"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Here are three different approaches for designing a sustainable urban transportation system for a city of 1 million people:\n",
            "\n",
            "**Approach 1: Comprehensive Public Transportation Network**\n",
            "\n",
            "* Develop a comprehensive network of buses, trams, and trains that cover the entire city, with frequent services and routes optimized for efficiency and passenger convenience.\n",
            "* Implement a smart traffic management system to minimize congestion and reduce travel times.\n",
            "* Encourage the use of public transportation by offering affordable fares, convenient payment options, and real-time information for passengers.\n",
            "* Invest in electric and hybrid vehicles to reduce greenhouse gas emissions and improve air quality.\n",
            "* Develop pedestrian-friendly and cyclist-friendly infrastructure to promote non-motorized transportation.\n",
            "\n",
            "**Approach 2: Shared Mobility and Autonomous Vehicles**\n",
            "\n",
            "* Implement a shared mobility system that allows citizens to use electric or hybrid vehicles for short trips, reducing the need for personal car ownership.\n",
            "* Introduce autonomous vehicles for public transportation, reducing labor costs and improving safety.\n",
            "* Develop a network of charging stations for electric vehicles and incentivize the adoption of eco-friendly vehicles.\n",
            "* Implement smart traffic management systems to optimize traffic flow and reduce congestion.\n",
            "* Create designated lanes for autonomous vehicles to ensure safe and efficient travel.\n",
            "\n",
            "**Approach 3: Mixed-Use Development and Pedestrian-Friendly Infrastructure**\n",
            "\n",
            "* Encourage mixed-use development by zoning areas for residential, commercial, and recreational activities, reducing the need for lengthy commutes.\n",
            "* Develop pedestrian-friendly infrastructure, including wide sidewalks, bike lanes, and public spaces, to promote walking and cycling.\n",
            "* Implement a shuttle service that connects residents to nearby amenities and public transportation hubs.\n",
            "* Invest in green infrastructure, such as parks and green roofs, to reduce urban heat islands and improve air quality.\n",
            "* Encourage the use of electric or hybrid vehicles for personal transportation and provide incentives for eco-friendly vehicle adoption.\n",
            "\n",
            "Now, let's evaluate these approaches:\n",
            "\n",
            "**Evaluation Criteria:**\n",
            "\n",
            "1. Environmental Impact\n",
            "2. Cost Effectiveness\n",
            "3. Passenger Experience\n",
            "4. Scalability\n",
            "5. Equity and Accessibility\n",
            "\n",
            "**Evaluation Results:**\n",
            "\n",
            "* Approach 1: Comprehensive Public Transportation Network\n",
            "\t+ Strengths: comprehensive coverage, efficient services, and reduced emissions.\n",
            "\t+ Weaknesses: high upfront costs, potential for congestion, and limited flexibility.\n",
            "\t+ Score: 8/10\n",
            "* Approach 2: Shared Mobility and Autonomous Vehicles\n",
            "\t+ Strengths: reduced emissions, increased efficiency, and improved safety.\n",
            "\t+ Weaknesses: high costs for infrastructure and maintenance, potential job displacement.\n",
            "\t+ Score: 7.5/10\n",
            "* Approach 3: Mixed-Use Development and Pedestrian-Friendly Infrastructure\n",
            "\t+ Strengths: reduced emissions, increased walkability, and improved air quality.\n",
            "\t+ Weaknesses: limited scalability, potential for gentrification and displacement.\n",
            "\t+ Score: 7/10\n",
            "\n",
            "**Best Solution:**\n",
            "\n",
            "Based on the evaluation results, I recommend Approach 1: Comprehensive Public Transportation Network as the best solution. This approach offers a comprehensive network of public transportation services, which can effectively reduce emissions and improve passenger convenience. While it has high upfront costs, it can be scaled up to accommodate the city's growing population. Additionally, it can be integrated with other approaches, such as shared mobility and pedestrian-friendly infrastructure, to create a more sustainable and efficient transportation system.\n",
            "\n",
            "**Implementation Plan:**\n",
            "\n",
            "1. Conduct a thorough feasibility study to identify the most suitable public transportation options for the city.\n",
            "2. Develop a comprehensive network of buses, trams, and trains, with frequent services and optimized routes.\n",
            "3. Implement a smart traffic management system to minimize congestion and reduce travel times.\n",
            "4. Offer affordable fares and convenient payment options to encourage the use of public transportation.\n",
            "5. Invest in electric and hybrid vehicles to reduce greenhouse gas emissions and improve air quality.\n",
            "6. Develop pedestrian-friendly and cyclist-friendly infrastructure to promote non-motorized transportation.\n",
            "7. Monitor and evaluate the effectiveness of the public transportation system and make adjustments as needed.\n"
          ]
        }
      ],
      "source": [
        "problem =  \"Design a sustainable urban transportation system for a city of 1 million people.\"\n",
        "response = chain.invoke({\"input\": problem})\n",
        "print(response.content)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ja7ZCUY2MJT2"
      },
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
